/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.mvc.util;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jianggujin.modulelink.mvc.converter.JTypeConverter;
import com.jianggujin.modulelink.util.JStringUtils;

/**
 * 注入工具
 * 
 * @author jianggujin
 *
 */
public class JInjector {
   /**
    * 创建实例对象
    * 
    * @param objClass
    * @return
    */
   private static <T> T createInstance(Class<T> objClass) {
      try {
         return objClass.newInstance();
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   @SuppressWarnings("unchecked")
   public static final <T> T injectBean(Class<T> beanClass, Map<String, ?> parasMap, boolean skipConvertError) {
      Object bean = createInstance(beanClass);
      JTypeConverter converter = JTypeConverter.getInstance();
      Method[] methods = beanClass.getMethods();
      for (Method method : methods) {
         String methodName = method.getName();
         if (methodName.startsWith("set") == false || methodName.length() <= 3) { // only
                                                                                  // setter
                                                                                  // method
            continue;
         }
         Class<?>[] types = method.getParameterTypes();
         if (types.length != 1) { // only one parameter
            continue;
         }

         String attrName = JStringUtils.firstCharToLowerCase(methodName.substring(3));
         if (parasMap.containsKey(attrName)) {
            try {
               String paraValue = JWebUtils.getFirstParam(parasMap.get(attrName));
               Object value = paraValue != null ? converter.convert(types[0], paraValue) : null;
               method.invoke(bean, value);
            } catch (Exception e) {
               if (skipConvertError == false) {
                  throw new RuntimeException(e);
               }
            }
         }
      }

      return (T) bean;
   }

   @SuppressWarnings("unchecked")
   public static final <T> T injectBean(Class<T> beanClass, HttpServletRequest request, boolean skipConvertError) {
      return (T) injectBean(beanClass, request.getParameterMap(), skipConvertError);
   }

}
